<template>
  <el-table :data="tableData" style="width: 100%;" size="large">
    <el-table-column label="模板名称" prop="name"/>
    <el-table-column label="文件路径" prop="path"/>
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          生成
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      style="position: fixed;top:92%;left: 45%"
      :page-size="pageDate.size"
      :pager-count="11"
      layout="prev, pager, next"
      :total="pageDate.total"
      v-model:current-page="pageDate.page"
  />

  <el-dialog v-model="dialogFormVisible" title="文件生成" width="500" center align-center>
    <el-form :model="ModelInfo">
      <el-form-item label="文件名" label-width="4rem">
        <el-input v-model="ModelInfo.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="数据" label-width="4rem">
        <el-input v-model="ModelInfo.data" type="textarea" rows="3" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="success" @click="UpdateMedel">
          保存
        </el-button>
        <el-button type="primary" @click="download">
          生成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import {onMounted, Ref, ref, UnwrapRef, watch} from "vue";
import {deleteFile, downloadFile, page, updateFile} from "../service/http.ts";
import {ElMessage, ElMessageBox} from "element-plus";

interface User {
  id: string
  name: string
  path: string
  data: string
}

const ModelInfo = ref({
  id: "",
  name: "",
  path: "",
  data: "",
})

const dialogFormVisible = ref(false)

const pageDate = ref({
  page: 1,
  size: 10,
  total: 100,
})

const handleEdit = (index: number, row: User) => {
  console.log(index, row)
  dialogFormVisible.value = true;
  ModelInfo.value.id = row.id;
  ModelInfo.value.path = row.path;
  ModelInfo.value.name = row.name;
  ModelInfo.value.data = JSON.parse(row.data);
}
const handleDelete = (index: number, row: User) => {
  console.log(index, row)
  DeleteItem(row.id);
}

const tableData: Ref<UnwrapRef<any[]>> = ref([])

onMounted(() => {
  pageList();
})

watch(() => pageDate.value.page, () => {
  pageList();
})

const pageList = () => {
  page(pageDate.value).then(res => {
    const dataFrom = res.data;
    if (dataFrom.code != 200) {

    } else {
      pageDate.value.total = dataFrom.data.total;
      tableData.value = dataFrom.data.records;
      console.log(tableData.value)
    }
    console.log(tableData);
  }).catch(err => {
    console.log(err)
  })
}

const DeleteItem = (id: string) => {
  ElMessageBox.confirm(
      '确定删除该模板？',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteFile(id)
            .then(res => {
              if (res.data.code === 200) {
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                })
                location.reload()
              } else {
                ElMessage({
                  type: 'error',
                  message: '删除失败',
                })
              }
            })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

const UpdateMedel = () => {
  const info = {
    id: ModelInfo.value.id,
    name: ModelInfo.value.name,
    data:JSON.stringify(ModelInfo.value.data),
    path: ModelInfo.value.path,
  }
  updateFile(info)
      .then(res => {
        if (res.data.code === 200) {
          ElMessage({
            type: 'success',
            message: '保存成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: '保存失败',
          })
        }
      })
}

const download = () => {
  const info = {
    id: ModelInfo.value.id,
  }
  downloadFile(info).then(res => {
    console.log(res)
    if (!res.data) return
    console.log(res.config.headers.get('content-disposition'))
    const fileNameEncode = res.headers['content-disposition']
        .split('filename=')[1]
        .split(';')[0];
    console.log(fileNameEncode)
    const fileName = decodeURI(fileNameEncode, "utf-8");
    console.log(fileName)
    const blob = new Blob([res.data]);
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.click();
    URL.revokeObjectURL(url);
  })
}
</script>
